<?php

namespace app\middleware\web;

use app\service\api\AuthServiceFacade;
use app\service\api\MemberServiceFacade;
use laytp\BaseMiddleware;
use think\Request;

class Auth extends BaseMiddleware
{
    /**
     * 执行中间件
     * @param Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle(Request $request, \Closure $next)
    {
        if (AuthServiceFacade::needLogin()) {
            // 为了兼容windows和linux获取header中驼峰命名的参数修改
            // windows中，使用原样获取，比如laytpWebToken
            // linux中，驼峰需要转换成短横杆获取，比如laytpWebToken要使用laytp-web-token来获取
            $token = $_COOKIE['laytpWebToken'] ?? $_COOKIE['laytpWebToken'] ?? $_COOKIE['laytpWebToken'] ?? '';
            $initUser = MemberServiceFacade::init( $token );

            if (!$initUser) return $this->error(MemberServiceFacade::getError(), 10401);
            if (!MemberServiceFacade::isLogin()) {
                if ($request->isAjax()) {

                    return $this->error('登录信息已过期', 10401);
                } else {
                    return redirect('/web/login.html');
                }
            }
        }
        return $next($request);
    }
}